import React, {createContext, useEffect, useReducer} from 'react'

import {getCollectorList, getChains} from '../api'

export const collectorsContext = createContext({collectorList: []})

export const castChainsContext = createContext({castChains: []})

export const commonContext = createContext({collectorList: [], castChains: []})

const UPDATE_CASTCHAINS = 'UPDATE_CASTCHAINS'
const UPDATE_COLLECTORELIST = 'UPDATE_COLLECTORELIST'

const reducer = (state, action) => {
  switch (action.type) {
    case UPDATE_COLLECTORELIST:
      return {...state, collectorList: action.payload}
    case UPDATE_CASTCHAINS:
      return {...state, castChains: action.payload}
    default:
      return state
  }
}

export default ({name, children}) => {

  const [state, dipatch] = useReducer(reducer, {collectorList: [{a: 1}], castChains: [{b: 2}]})

  useEffect(() => {

    let didCancel = false

    /*getChains({_m:'fetch'}).then( res => {
      const {data} = res
      if(!didCancel){
        dipatch({type:'UPDATE_CASTCHAINS', payload:data})
      }
    })

    getCollectorList({
      _m:'fetch'
    }).then(res =>{
      if(!didCancel){
        dipatch({type:'UPDATE_COLLECTORELIST', payload:res.data.rows})
      }
    })*/

    return () => {
      didCancel = true
    }

  }, [])

  const {collectorList, castChains} = state

  let component = <React.Fragment></React.Fragment>
  switch (name) {
    case 'collectorsContext':
      component = (
        <collectorsContext.Provider value={{collectorList}}>
          {children}
        </collectorsContext.Provider>
      )
      break;
    case 'castChainsContext':
      component = (
        <castChainsContext.Provider value={{castChains}}>
          {children}
        </castChainsContext.Provider>
      )
      break;
    case 'commonContext':
      component = (
        <commonContext.Provider value={{collectorList, castChains}}>
          {children}
        </commonContext.Provider>
      )
      break;
    default:
      break;
  }
  return component
}

